package com.netty.java.nio.groupchat;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @Author: TongRui乀
 * @Date: 2020-05-04 9:44
 * @description： 群聊客户端
 */
@Slf4j
public class GroupChatClient {

    private static final int SERVER_PORT = 8888;

    private Selector selector;

    private SocketChannel socketChannel;

    private String name;

    public GroupChatClient() {

        try {
            selector = Selector.open();

            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", SERVER_PORT));

            socketChannel.configureBlocking(false);

            socketChannel.register(selector, SelectionKey.OP_READ);

            name = socketChannel.getLocalAddress().toString().substring(1);

            log.info("客户端启动成功：{}", name);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 接收消息
     */
    public void accept() {

        try {
            while (true) {

                if (selector.select(1000) < 1) {
                    continue;
                }

                Set<SelectionKey> selectionKeys = selector.selectedKeys();

                Iterator<SelectionKey> iterator = selectionKeys.iterator();

                while (iterator.hasNext()){

                    SelectionKey key = iterator.next();

                    try {
                        if(key.isReadable()){
                            SocketChannel channel = (SocketChannel) key.channel();

                            ByteBuffer readBuffer = ByteBuffer.allocate(1024);

                            int read = channel.read(readBuffer);

                            if (read > 0) {
                                String message = new String(readBuffer.array());

                                log.info("接收到消息:{}", message);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                // todo ???
                iterator.remove();
            }
        } catch (IOException e) {
            log.error("获取消息失败:{}", e.getMessage());
        }

    }

    public void send(String message) {

        String info = name + "_" + message;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        GroupChatClient client = new GroupChatClient();

        // 启动一个线程 监听消息
        new Thread(client::accept).start();

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            client.send(s);
        }

    }

}
